package com.wm.javamall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wm.common.exception.NoStockException;
import com.wm.common.to.mq.OrderTo;
import com.wm.common.to.mq.StockDetailTo;
import com.wm.common.to.mq.StockLockedTo;
import com.wm.common.utils.PageUtils;
import com.wm.common.utils.Query;
import com.wm.common.utils.R;
import com.wm.javamall.order.entity.OrderEntity;
import com.wm.javamall.order.service.OrderService;
import com.wm.javamall.product.controller.SkuInfoController;
import com.wm.javamall.ware.dao.WareSkuDao;
import com.wm.javamall.ware.entity.WareOrderTaskDetailEntity;
import com.wm.javamall.ware.entity.WareOrderTaskEntity;
import com.wm.javamall.ware.entity.WareSkuEntity;
import com.wm.javamall.ware.service.WareOrderTaskDetailService;
import com.wm.javamall.ware.service.WareOrderTaskService;
import com.wm.javamall.ware.service.WareSkuService;
import com.wm.javamall.ware.vo.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Slf4j
@Service("wareSkuService")
@RabbitListener(queues = "stock.release.stock.queue")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private SkuInfoController skuInfoController;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    OrderService orderService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId) && !"0".equalsIgnoreCase(skuId)) {
            queryWrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId) && !"0".equalsIgnoreCase(wareId)) {
            queryWrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {

        //1、判读如果没有这个库存记录新增
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(
                new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));

        if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //远程查询sku的名字，如果失败整个事务无需回滚
            //1、自己catch异常
            try{
                R info = skuInfoController.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }
            //添加库存信息
            wareSkuDao.insert(wareSkuEntity);
        } else {
            //修改库存信息
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

    /**
     * 判断是否有库存
     *
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> skuHasStockVos = skuIds.stream().map(item -> {
            Long count = this.baseMapper.getSkuStock(item);
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(item);
            skuHasStockVo.setHasStock(count == null?false:count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return skuHasStockVos;
    }

    /**
     * 为某个订单锁定库存
     *默认只要是运行时异常都会回滚
     *
     *库存解锁的场景
     * 1、下订单成功，订单过期没有支付被系统自动取消，被用户手动取消，都要解锁库存
     * 2、下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚
     *    之前解锁的库存就要自动解锁
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public boolean orderLockStock(WareSkuLockVo vo) {
        /**
         * 保存库存工作单的详情
         *
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        //1、按照下单的收货地址，找到一个就近仓库，锁定库存
        //1、找到每个商品在哪个仓库都有库存
        List<com.wm.javamall.order.vo.OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        //2、锁定库存
        for (SkuWareHasStock hasStock : collect) {
            boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                //没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            //1、如果每个商品都锁定成功，将当前商品锁定了几件的工作单记录发送给MQ
            //2、如果锁定失败，前面保存的工作的回滚，发送出去的消息，即使要解锁记录，由于去数据库查不到id,所以就不用解锁
            //
            for (Long wareId : wareIds) {
                //成功就返回1，否则为0
                Long count = wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if(count == 1){
                    skuStocked = true;
                    // 告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity entity =
                            new WareOrderTaskDetailEntity(null, skuId, null, hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(entity);
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(entity,stockDetailTo);
                    //只发id不行，防止回滚以后找不到数据
                    lockedTo.setDetail(stockDetailTo);

                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                    break;
                } else {
                    //当前仓库锁失败，重试下一个仓库
                }
            }
            if(skuStocked == false){
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }

        //3、肯定全部锁定成功

        return true;
    }

    /**
     * 1、库存自动解锁
     * 下订单成功，库存锁定成功，接下来的业务调用失败，
     * 导致订单回滚，之前解锁的库存就要自动解锁
     * 2、订单失败
     *
     * 只要解锁库存的消息失败，一定要告诉服务解锁失败
     */
    @Override
    public void unlockStock(StockLockedTo to) {

        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        //解锁
        //1、查询数据库关于这个订单的锁定库存信息
        //有：证明库存锁定成功
        //    解锁：订单情况：1.没有这个订单，必须解锁
        //                 2.有这个订单。不是解锁库存。
        //                      订单状态：已取消：解锁库存
        //                              没取消：不能解锁
        //没有：库存锁定失败，库存回滚了，这种情况无需解锁
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if(byId != null){
            //解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            OrderEntity orderByOrderSn = orderService.getOrderByOrderSn(orderSn);
            if(orderByOrderSn == null || orderByOrderSn.getStatus() == 4){
                //订单不存在，订单已经被取消了，才能解锁库存
                //detailId
                if(byId.getLockStatus() == 1){
                    //当前库存工作单详情，状态1 已锁定但是未解锁才可以解锁
                    unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                }
            }
        } else {
            //无需解锁
        }
    }

    //防止订单服务卡顿，导致订单状态消息一直改不了，库存消息优先到期，查订单状态新建状态，
    //导致卡顿的订单，永远不能解锁库存
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查一下最新库存的状态，防止重复解锁库存
        WareOrderTaskEntity taskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        if (Objects.nonNull(taskEntity)){
            Long id = taskEntity.getId();
            //按照工作单找到所有没有解锁的库存，进行解锁
            List<WareOrderTaskDetailEntity> entities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                    .eq("task_id", id)
                    .eq("lock_status", 1));
            for (WareOrderTaskDetailEntity entity : entities) {
                unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
            }
        }
    }

    @Override
    public void saveWare(WareSkuEntity wareSku) {
        wareSku.setWareId(1l);
        R info = skuInfoController.info(wareSku.getSkuId());
        log.info("远程查询sku信息：r={}", info);
        SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>(){});
        if (Objects.isNull(skuInfo)){
            // 为空 说明没有这个sku
            return;
        }
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("sku_id", wareSku.getSkuId());
        WareSkuEntity wareSkuEntity = this.getOne(wrapper);
        if (Objects.isNull(wareSkuEntity)){
            // 为空说明仓库没有这个商品的库存
            wareSku.setSkuName(skuInfo.getSkuName());

            this.save(wareSku);
        } else {
            // 不为空直接在基础上添加即可
            wareSkuEntity.setStock(wareSkuEntity.getStock() + wareSku.getStock());
            this.updateById(wareSkuEntity);
        }

    }

    @Override
    public void minusWare(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = wareOrderTaskEntity.getId();
        //按照工作单找到所有锁定的库存
        List<WareOrderTaskDetailEntity> entities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : entities) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
            Long skuId = entity.getSkuId();
            Integer skuNum = entity.getSkuNum();
            UpdateWrapper<WareSkuEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("sku_id", skuId)
                    .setSql("stock = stock - " + skuNum);
            this.update(updateWrapper);
        }
    }



    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId){
        //库存解锁
        wareSkuDao.unLockStock(skuId,wareId,num);
        //更新库存工作单的状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        //变为已解锁
        entity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(entity);
    }



    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }
}